//
//  YWDouyinController.m
//  YueshengToutiao
//
//  Created by jun peng on 2022/5/22.
//  Copyright © 2022 YW. All rights reserved.
//

#import "YWDouyinController.h"
#import "YWLittleVideoTool.h"
#import "YWGetNewsListParam.h"
#import "YWGetNewsListStatus.h"
#import "YWGetNewsResultStatus.h"
#import "YWGetNewsDataStatus.h"

#import "YWNavigationController.h"

#import "YWLittleVideoPlayerCell2.h"

#import "YWLittleVideoPlayerView.h"


#define Pagesize @"15"

@interface YWDouyinController ()<UITableViewDelegate,UITableViewDataSource,YWLittleVideoPlayerViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong)NSMutableArray <YWGetNewsDataStatus *>*statusArray;

@property (nonatomic,assign)NSInteger page;

@property (nonatomic, strong) YWLittleVideoPlayerView * vedioView; // 播放器

@end

@implementation YWDouyinController

-(NSMutableArray*)statusArray{
    if (_statusArray == nil) {
        _statusArray = [NSMutableArray array];
    }
    return _statusArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    
    self.navBar.backgroundColor = [UIColor clearColor];
    
    [self setupTableView];
    
    MJWeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [weakSelf loadNewsData];
    }];
    //加载接口
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.scrollsToTop = NO;
    
    // 创建播放器
    self.vedioView = [YWLittleVideoPlayerView littleVideoPlayerView];
    self.vedioView.delegate = self;
    [self.tableView addSubview:self.vedioView];
    self.vedioView.backgroundColor = [UIColor blackColor];
    self.vedioView.hidden = YES;
    
    
}

-(void)setupTableView{
    
    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.pagingEnabled = YES;
    
    //写了这句话就不会露出上拉控件，所以以后每个tableView都要写
        if (@available(iOS 11.0, *)) {
            
            self.tableView.estimatedRowHeight = 0;
            
            self.tableView.estimatedSectionFooterHeight = 0;
            
            self.tableView.estimatedSectionHeaderHeight=0;
            self.tableView.contentInsetAdjustmentBehavior= UIScrollViewContentInsetAdjustmentNever;
            
        }
        
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    self.tableView.showsVerticalScrollIndicator = NO;
}



-(void)loadNewsData{
    
    self.page = 1;
    YWGetNewsListParam *param = [[YWGetNewsListParam alloc] init];
    param.pagesize = Pagesize;
    param.currentpage = [NSString stringWithFormat:@"%ld",(long)self.page];
    NSString *newsID = @"fa214b6eed7949f5a5c32feeab028e89";
    param.newsid = newsID;
    NSString *userID = self.meStatus.userStatus.Id;
      if (userID != nil) {
           param.userid = userID;
       }
       else{
           
           param.userid = @"";
       }
    
    [YWLittleVideoTool getVideoListStatusesWithParameters:param success:^(YWGetNewsListStatus * _Nonnull status) {
        
        [self.tableView.mj_header endRefreshing];
        if (status.IsSuccess.integerValue == 1) {
            
            //先缓存所有封面图和头像图
            [self dowloadImg:status];
            
            self.statusArray = [NSMutableArray arrayWithArray: status.ResultObj.PageInfo];
            
             //刷新列表
             [self.tableView reloadData];
            
            
            //预加载
            NSMutableArray *urlArray = [NSMutableArray array];
            for (YWGetNewsDataStatus *dataStatus in status.ResultObj.PageInfo) {
                [urlArray addObject:dataStatus.FileUrl];
            }
            YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
            [playerManager preLoadUrlArray:urlArray];
            
            
            //播放第一个视频
            [self playerViewPlayWithIndex:0];
            
            
            //假如少于就不需要添加上拉控件了
           if (status.ResultObj.PageInfo.count == param.pagesize.integerValue) {
            
               //添加上拉刷新控件
               MJWeakSelf
              self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

                  [weakSelf loadMoreData];
              }];
               
            }
           
        }
        else{
            
            self.statusArray = [NSMutableArray array];
            
            [self.tableView reloadData];
            
//            [MBProgressHUD showError:status.Message];
            
            //假如没数据、播放器可以播回之前的视频不用理它
            
        }
    } failure:^(NSError * _Nonnull error) {
        
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD showError:@"服务器繁忙，请稍后再试"];
    }];
    
}

-(void)loadMoreData{
    self.page ++;
    YWGetNewsListParam *param = [[YWGetNewsListParam alloc] init];
    param.pagesize = Pagesize;
    param.currentpage = [NSString stringWithFormat:@"%ld",(long)self.page];
    
    NSString *newsID = @"fa214b6eed7949f5a5c32feeab028e89";
    param.newsid = newsID;
    NSString *userID = self.meStatus.userStatus.Id;
      if (userID != nil) {
           param.userid = userID;
       }
       else{
           
           param.userid = @"";
       }
    
    [YWLittleVideoTool getVideoListStatusesWithParameters:param success:^(YWGetNewsListStatus * _Nonnull status) {
        
        [self.tableView.mj_footer endRefreshing];
        if (status.IsSuccess.integerValue == 1) {
            
            //先缓存所有封面图和头像图
            [self dowloadImg:status];
            
            [self.statusArray addObjectsFromArray:status.ResultObj.PageInfo];
            [self.tableView reloadData];
            
            //预加载
            NSMutableArray *urlArray = [NSMutableArray array];
            for (YWGetNewsDataStatus *dataStatus in status.ResultObj.PageInfo) {
                [urlArray addObject:dataStatus.FileUrl];
            }
            YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
            [playerManager preLoadUrlArray:urlArray];
            
            
        }
        else{
            
            //它做的接口没数据是走这里的、所以可以直接移除footer
            [self.tableView.mj_footer removeFromSuperview];
            [MBProgressHUD showError:status.Message];
            
        }
    } failure:^(NSError * _Nonnull error) {
        
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:@"服务器繁忙，请稍后再试"];
    }];
    
    
}

-(void)dowloadImg:(YWGetNewsListStatus *)status{
    for (YWGetNewsDataStatus *dataStatus in status.ResultObj.PageInfo) {
       
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:dataStatus.AuthorImg] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        }];
        
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:dataStatus.Img] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            YWLog(@"aaabbbcccddd");
        }];
    }
}

//////////////////////////////////////////////////////////////////
#pragma mark - tableView代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.statusArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YWLittleVideoPlayerCell2 *cell = [YWLittleVideoPlayerCell2 cellWithTableView:tableView];
    cell.status = self.statusArray[indexPath.row];
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return self.tableView.height;
}

-(void)viewWillAppear:(BOOL)animated{

     [super viewWillAppear:animated];
    
    
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.tabBarController.tabBar.backgroundColor = [UIColor blackColor];

}
-(void)viewWillDisappear:(BOOL)animated{

     [super viewWillDisappear:animated];
    
    
   self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
    self.tabBarController.tabBar.backgroundColor = [UIColor whiteColor];

}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    //拿出当前cell
    NSArray *cellArray = [self.tableView visibleCells];
    
    if (cellArray.count != 0) {
        YWLittleVideoPlayerCell2 *showingCell = cellArray[0];
        
        NSIndexPath *showingIndexPath = [self.tableView indexPathForCell:showingCell];
        NSInteger showingIndex = showingIndexPath.row;
        
        //已经滚到了另外一页
        if (showingIndex != self.vedioView.index) {
            
            //播放当前的
            [self playerViewPlayWithIndex:showingIndex];
            
        }
    }
    
}

//播放
-(void)playerViewPlayWithIndex:(NSInteger)showingIndex{
    
    self.vedioView.frame = CGRectMake(0, showingIndex * self.tableView.height, Wi, self.tableView.height);
    
    YWGetNewsDataStatus *status = self.statusArray[showingIndex];
    
    self.vedioView.index = showingIndex;
    
    self.vedioView.status = self.statusArray[showingIndex];
    
    [self.vedioView startPlayWithUrl:status.FileUrl withMute:NO];
    
    self.vedioView.hidden = NO;
}


//全屏返回手势方法（写了下面的触摸点在子VC也能全屏手势返回）
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    //当前状态是stop状态、并且vedioView因为tableView已经加载完有东西的
    if (!self.vedioView.isPlaying_containPause && self.vedioView.urlString != nil) {
        
        
        //播放当前的
        [self playerViewPlayWithIndex:self.vedioView.index];
        
        
    }
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    self.vedioView.hidden = YES;
    
    [self.vedioView stopPlay];
    
}


@end
